package com.qf.sy2103.springboot.Filter;


import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

//获取前端控制器的中得数据
@Slf4j
@WebFilter(urlPatterns = {"/*"})
public class HandlerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //先转换为 HttpServeletRequest和 HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) req;//基本只用request获取
        HttpServletResponse response = (HttpServletResponse) res;//获取相应的信息
//        //获取请求行数据
        log.debug("========================URL==========================");
        String requestURI = request.getRequestURI();
        log.debug("url {}",requestURI);
//        //获取请求头中某一行的数据
//        String host = request.getHeader("HOST");
//        log.debug("host: {}",host);
        log.debug("=====================请求头中数据========================");
        //获取请求头中的所有数据 会返回一个枚举类型的数据 遍历它
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            log.debug("{}--->{}",s,header);
        }

        log.debug("==================参数是===================");
        Map<String, String[]> parameterMap = request.getParameterMap();//获取所有参数
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();//将map转换为set
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();//获取key
            String[] value = entry.getValue();//获取value
            log.debug("{}--->{}",key,value);
        }
        chain.doFilter(request,response);

        //分析相应结果
        log.debug("==================响应数据===================");
        //相应状态码
        int status = response.getStatus();
        log.debug("响应码为: {}",status);
        //获取响应头的name
        Collection<String> headerNames1 = response.getHeaderNames();
        for (String s : headerNames1) {
            String header = response.getHeader(s);//获取每个相应name对应的值
            log.debug("{}--->{}",s,header);
        }
    }

    @Override
    public void destroy() {

    }
}
